$(document).on('pageinit', function() {
    $('#advance_option').hide();
    $('#brand').val('');

    $('#advance_option_toggle').click(function(){
        if ($('#advance_option').is(':hidden')) {
            $('#advance_option').show(200);
            $('#advance_option_toggle')
                    .attr('data-icon', 'arrow-u')
                    .children().children().next().removeClass('ui-icon-arrow-d').addClass('ui-icon-arrow-u');
        }
        else {
            $('#advance_option').hide(200);
            $('#advance_option_toggle')
                    .attr('data-icon', 'arrow-d')
                    .children().children().next().removeClass('ui-icon-arrow-u').addClass('ui-icon-arrow-d');
        }
    });

    var marked = [];
    var value = '';

    $('.brand').each(function(id) {
        if ($(this).is(':checked')) {
            marked[id] = true;
            if (value != '') value += ' ';
            value += $(this).attr('value');
        }
        else marked[id] = false;
    });
    $('#brand').val(value);

    $('.brand').change(function(event) {
        var id = $(event.target).attr('id');
        id = id.substr(0, id.indexOf('-')) - 1;

        marked[id] = !marked[id];

        var value = '';
        $('.brand').each(function(id) {
            if (marked[id]) {
                if (value != '') value += ' ';
                value += $(this).attr('value');
            }
        });
        $('#brand').val(value);
    });
});
